package com.douding.file.controller.admin;

import com.douding.server.domain.File;
import com.douding.server.dto.FileDto;
import com.douding.server.dto.ResponseDto;
import com.douding.server.enums.FileUseEnum;
import com.douding.server.service.FileService;
import com.douding.server.service.TestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Objects;

/*
    返回json 应用@RestController
    返回页面  用用@Controller
 */
@RequestMapping("/admin/file")
@RestController
public class UploadController {

    private static final Logger LOG = LoggerFactory.getLogger(UploadController.class);
    public static final String BUSINESS_NAME = "文件上传";
    @Resource
    private TestService testService;

    @Value("${file.path}")
    private String FILE_PATH;

    @Value("${file.domain}")
    private String FILE_DOMAIN;

    @Resource
    private FileService fileService;

    @RequestMapping("/upload")
    public ResponseDto upload(@RequestBody FileDto fileDto) throws Exception {
        // 获取文件类型
        String type = Objects.requireNonNull(FileUseEnum.getByCode(fileDto.getUse())).getDesc();

        //保存到数据库
        fileDto.setPath(Paths.get(type, fileDto.getName()).toString());
        fileService.save(fileDto);

        //构建文件路径
        Path directoryPath = Paths.get(System.getProperty("user.dir"));
        Path fullPath = directoryPath.resolve(FILE_PATH).resolve(type).resolve(fileDto.getName());
        fileDto.setPath(FILE_DOMAIN + type + "/" + fileDto.getName());

        //合并分片
        merge(fileDto, fullPath);

        // 设置响应
        ResponseDto responseDto = new ResponseDto();
        responseDto.setContent(fileDto);
        return responseDto;
    }

    private void merge(FileDto fileDto, Path fullPath) throws IOException {
        // 处理并保存文件
        if (fileDto.getShard().contains(",")) {
            byte[] decodedBytes = Base64.getDecoder().decode(fileDto.getShard().substring(fileDto.getShard().indexOf(",") + 1));
            Files.write(fullPath, decodedBytes);
        } else {
            throw new IllegalArgumentException("Invalid base64 data format.");
        }

    }


    @GetMapping("/check/{key}")
    public ResponseDto check(@PathVariable String key) throws Exception {

        LOG.info("检查上传分片开始：{}", key);

        File file = fileService.selectByKey(key);
        if (file != null) {

            return null;
        }
        return new ResponseDto();
    }

}//end class
